package com.itc.bi.easyExcelListener;

/**
 * @BelongsProject: itc-airport-cloud
 * @BelongsPackage: com.itc.bi.easyExcelListener
 * @Author: hecaiy
 * @CreateTime: 2024-09-17  18:03
 * @Description: TODO
 * @Version: 1.0
 */
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import java.util.*;

import com.alibaba.excel.exception.ExcelAnalysisException;

import java.util.ArrayList;
import java.util.List;

public class LimitedDataListenerss extends AnalysisEventListener<LinkedHashMap<Integer, String>> {
    private static final int LIMIT = 100; // 你可以传递这个限制条数，或者在构造函数中设置
    private int count = 0;  // 计数器
    private List<LinkedHashMap<Integer, String>> dataList = new ArrayList<>();  // 保存读取的数据
    private final int limit;  // 读取的最大条数

    // 构造函数，传入需要读取的条数限制
    public LimitedDataListenerss(int limit) {
        this.limit = limit;
    }

    @Override
    public void invoke(LinkedHashMap<Integer, String> data, AnalysisContext context) {
        count++;
        // 保存数据到 dataList，直到达到指定条数
        if (count <= limit) {
            dataList.add(data);
        }
        // 达到条数限制，停止读取
        if (count >= limit) {
            throw new ExcelAnalysisException("读取数据已达到指定条数限制");  // 中断读取
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        System.out.println("读取完毕，读取的总条数：" + count);
    }

    // 获取读取到的数据
    public List<LinkedHashMap<Integer, String>> getDataList() {
        return dataList;
    }
}


